package top.ply.shopservice.service.impl;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import top.ply.common_unit.constant.ConstantPool;
import top.ply.common_unit.entity.RespEntity;
import top.ply.common_unit.global_resp.RespUtil;
import top.ply.message.service.EmailMsgService;
import top.ply.message.service.TelephoneMsgService;
import top.ply.shopservice.service.ShopOwnerService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class ShopOwnerServiceImpl implements ShopOwnerService {

    @Autowired
    @Resource(name = "telephoneCodeRedisTemplate")
    RedisTemplate telephoneCodeRedisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public RespEntity sendRegisterCode(String telephone) {
        final String verifyCode = generateVerifyCode();
        new Thread(() -> {
            sendVerifyCode(telephone, verifyCode);
        }).start();
        SetOperations ops = telephoneCodeRedisTemplate.opsForSet();
        Long add = ops.add(telephone, verifyCode);
        return add > 0 ? RespUtil.baseSuccess() : RespUtil.baseFail();
    }

    @Override
    public void checkRegisterCode(String telephone, String code) {

    }

    private void sendVerifyCode(String address, String verifyCode) {
        Map<String, String> addressAndCode = new HashMap<>();
        if (ConstantPool.PHONE_PATTERN.matcher(address).matches()) {

            addressAndCode.put(EmailMsgService.sendToKey, address);
            addressAndCode.put(EmailMsgService.verifyCodeKey, verifyCode);
            Message<Map<String, String>> message = MessageBuilder.withPayload(addressAndCode).build();
            rabbitTemplate.convertAndSend(message);

        } else if (ConstantPool.EMAIL_PATTERN.matcher(address).matches()) {

            addressAndCode.put(TelephoneMsgService.sendToKey, address);
            addressAndCode.put(TelephoneMsgService.VERIFY_CODE_KEY, verifyCode);
            Message<Map<String, String>> message = MessageBuilder.withPayload(addressAndCode).build();
            rabbitTemplate.convertAndSend(message);

        }
    }

    private String generateVerifyCode() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            char var = (char) (random.nextInt(26) + 65);
            sb.append(var);
        }
        return sb.toString();
    }
}
